/**
 * Copyright (c) 2010-2011 Pierre Labatut
 *
 * This file is part of Space-Chronicles project.
 *
 * Space-Chronicles is free software: you can redistribute it and/or modify it
 * under the terms of its license which may be found in the accompanying
 * LICENSE file or <http://code.google.com/p/space-chronicles/>.
 */
package space.app.meshview;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import space.app.common.Application;
import space.app.common.ApplicationBuilder;
import space.app.common.Server;
import space.app.common.ServerFrame;

/**
 *
 * @author Pierre
 */
public class MeshMain implements ApplicationBuilder<MeshMessage> {

    final URL meshDescriptionFile;

    /**
     * @param args
     * <ul>
     * <li>no args</li>
     * <li>-open "filepath"</li>
     * <ul>
     */
    public static void main(String args[]) throws MalformedURLException {
        /**
         * Parse the command line arguments
         */
        if (args == null) {
            throw new IllegalArgumentException("Unexpected code path");
        }
        final URL meshDescriptionFile;
        if (args.length == 0) {
            meshDescriptionFile = null;
        } else if (args.length == 2 && args[0].equals("-open")) {
            final File file = new File(args[1]);
            if(file.isFile())
                meshDescriptionFile = file.toURI().toURL();
            else
                meshDescriptionFile = new URL(args[1]);


        } else {
            throw new IllegalArgumentException("The program argument error:" + Arrays.asList(
                    args));
        }

        Application.run(new MeshMain(meshDescriptionFile));
    }

    public MeshMain(URL meshDescriptionFile) {
        this.meshDescriptionFile = meshDescriptionFile;
    }

    @Override
    public ServerFrame<MeshMessage> createFrame(Application<MeshMessage> application) {
        try {
            return new MeshFrame(application, meshDescriptionFile);
        } catch (MalformedURLException ex) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public Server<MeshMessage> createServer(Application<MeshMessage> application) {
        return new MeshServer(application);
    }
}
